<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateUserAPIRequest;
use App\Http\Requests\API\UpdateUserAPIRequest;
use App\Models\User;
use App\Models\WorkType;
use App\Repositories\UserRepository;
use App\Services\AuthCheckService;
use App\Services\SmsServices;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use link1st\Easemob\App\Easemob;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;


/**
 * Class UserController
 * @package App\Http\Controllers\API
 */
class UserAPIController extends AppBaseController
{
    /** @var  UserRepository */
    private $userRepository;
    private $sms;

    public function __construct(Request $request)
    {
        $this->userRepository = app(UserRepository::class);
        $this->middleware('auth:api', ['except' => ['register', 'getSmsCode', 'modifyPassword']]);
    }

    /**
     * Display a listing of the User.
     * GET|HEAD /users
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $this->userRepository->pushCriteria(new RequestCriteria($request));
        $this->userRepository->pushCriteria(new LimitOffsetCriteria($request));
        $users = $this->userRepository->all();

        return $this->sendResponse($users->toArray(), 'Users retrieved successfully');
    }

    /**
     * Store a newly created User in storage.
     * POST /users
     *
     * @param CreateUserAPIRequest $request
     *
     * @return Response
     */
    public function store(CreateUserAPIRequest $request)
    {
        $input = $request->all();

        $users = $this->userRepository->create($input);

        return $this->sendResponse($users->toArray(), 'User saved successfully');
    }

    /**
     * @api {get} api/users/:id 用户信息,为-1时候查看自己
     * @apiGroup User
     * @apiName show
     *
     * @apiHeader {String} Accept=application/json
     * @apiHeader {String} Authorization Bearer xxxxx
     *
     * @apiSampleRequest api/users/:id
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     * "code": 0,
     * "msg": "ok",
     * "data": {
     * "id": 1,
     * "name": "sky",
     * "nick_name": null,
     * "phone": "18002280102",
     * "user_type": null,
     * "work_type_ids": null,
     * "status": 0,
     * "avatar": null,
     * "address": null,
     * "province_id": null,
     * "city_id": null,
     * "district_id": null,
     * "created_at": "2017-08-15 15:35:11",
     * "updated_at": "2017-08-15 15:35:11",
     * "deleted_at": null
     * }
     * }
     */
    public function show($id)
    {
        /** @var User $user */
        if ($id != -1) {
            if (!AuthCheckService::checkIsSelf($id)) {
                $this->fail(4000, '无权限');
            }
            $user_id = $id;
        } else {
            $user_id = Auth::id();
        }

        $user = $this->userRepository->getUserDetail($user_id);

        if (empty($user)) {
            return $this->fail(-1, 'User not found');
        }
        $user['roles'] = $user->roles;
        return $this->success($user, 'User retrieved successfully');
    }

    /**
     * @api {put} api/users/:id 修改用户信息，密码 用户名除外
     * @apiGroup User
     * @apiName update
     *
     * @apiParam {Array} [work_type_ids]  工匠类型[id,id].
     * @apiParam {String} [avatar]  头像地址.
     * @apiParam {String} [nick_name]  昵称.
     * @apiParam {String} [real_name]  真实姓名.
     * @apiParam {Number} [work_age]  工龄.
     * @apiParam {String} [phone]  更换的手机号.
     *
     * @apiHeader {String} Accept=application/json
     * @apiHeader {String} Authorization Bearer xxxxx
     *
     * @apiSampleRequest api/users/:id
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     * }
     **/
    public function update($id, UpdateUserAPIRequest $request)
    {
        $input = $request->only(['work_type_ids', 'avatar', 'nick_name', 'real_name', 'work_age', 'phone']);
        if (!AuthCheckService::checkIsSelf($id)) {
            return $this->fail(4000, '无权限');
        }

        /** @var User $user */
        $user = $this->userRepository->findWithoutFail($id);

        if (empty($user)) {
            return $this->fail(-1, 'User not found');
        }
        if (!empty($input['work_type_ids'])) {
            $input['work_type_ids'] = json_encode($input['work_type_ids']);
        }

        $user = $this->userRepository->update($input, $id);

        return $this->success($user->toArray(), 'User updated successfully');
    }

    /**
     * @api {delete} api/users/:id 删除user
     * @apiGroup User
     * @apiName destroy
     *
     * @apiHeader {String} Accept=application/json
     * @apiHeader {String} Authorization Bearer xxxxx
     *
     * @apiSampleRequest api/users/:id
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     * }
     **/
    public function destroy($id)
    {
        /** @var User $user */
        if (!AuthCheckService::checkIsSelf($id)) {
            return $this->fail(4000, '无权限');
        }
        $user = $this->userRepository->findWithoutFail($id);

        if (empty($user)) {
            return $this->sendError('User not found');
        }

        $user->delete();

        return $this->sendResponse($id, 'User deleted successfully');
    }

    /**
     * @api {post} api/users/register 用户注册
     * @apiGroup User
     * @apiName register
     * @apiParam {String} phone  手机号.
     * @apiParam {String} password  密码.
     * @apiParam {String} code  验证码.
     * @apiSampleRequest api/users/register
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *
     *     }
     */
    public function register(Request $request)
    {
        $input = $request->all();
        $phone = $input['phone'];
        $password = $input['password'];
        $info = [
            'name' => $phone,
            'phone' => $phone,
            'status' => 1,
            'password' => md5($password)
        ];
        $user = $this->userRepository->create($info);
        dd(0);
        $input = $request->only(['phone', 'code', 'password']);

        $rules = array("phone" => "required",
            "code" => "required",
            "password" => "required"
        );
        $messages = array("phone.required" => "手机号为空",
            "code.required" => "验证码为空",
            "password.required" => "密码为空");
        $result = $this->validate($input, $rules, $messages);
        if ($result["code"] != 0) {
            return $this->fail(self::VALIDATE_ERROR, $result["errors"]);
        }

        $phone = $input['phone'];
        $code = $input['code'];
        $password = $input['password'];

        //判断是否已经注册
        $user = $this->userRepository->findByField('name', $phone)->toArray();

        if (!empty($user)) {
            return $this->fail(self::VALIDATE_ERROR, '该号码已经注册');
        }


        if (SmsServices::checkCaptcha($phone, $code, 1)) {
            $info = [
                'name' => $phone,
                'phone' => $phone,
                'status' => 1,
                'password' => md5($password)
            ];
            DB::beginTransaction();
            $user = $this->userRepository->create($info);
            if (!$user) {
                DB::rollBack();
                return $this->fail(-1, '服务器错误注册失败');
            }
            //注册环信
            $hx_user = \Easemob::publicRegistration(md5($user['id']), md5('king-kong' . $user['id']));
            if (!$hx_user) {
                DB::rollBack();
                return $this->fail(-1, '通信服务注册失败');
            }
            DB::commit();
            return $this->success($user);

        } else {
            return $this->fail(self::VALIDATE_ERROR, '验证码错误，请重试');
        }
    }

    /**
     * @api {get} api/users/sms/code/:type/:phone 获取验证码
     * @apiGroup User
     * @apiName getSmsCode
     * @apiParam {String} phone  手机号.
     * @apiParam {Number} type  短信类型 1 注册验证 2 找回密码
     * @apiSampleRequest api/users/sms/code/:type/:phone
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *            "code": 0,
     *            "msg": "ok",
     *            "data": 3911
     *     }
     */
    public function getSmsCode($type, $phone)
    {
        $result = SmsServices::getCaptcha($phone, $type);
        if ($result['code'] == 0) {
            return $this->success($result['captcha']);
        }
    }

    /**
     * @api {post} api/users/password/modify 更改密码
     * @apiGroup User
     * @apiName modifyPassword
     * @apiParam {String} phone  用户名（手机号）.
     * @apiParam {String} password  密码.
     * @apiParam {String} code  验证码.
     * @apiSampleRequest api/users/password/modify
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *
     *     }
     */
    public function modifyPassword(Request $request)
    {
        $input = $request->only(['phone', 'code', 'password']);

        $rules = array("phone" => "required",
            "code" => "required",
            "password" => "required"
        );
        $messages = array("phone.required" => "手机号为空",
            "code.required" => "验证码为空",
            "password.required" => "新密码为空");
        $result = $this->validate($input, $rules, $messages);
        if ($result["code"] != 0) {
            return $this->fail(self::VALIDATE_ERROR, $result["errors"]);
        }

        $phone = $input['phone'];
        $code = $input['code'];
        $password = $input['password'];

        //判断是否已经注册
        $user = $this->userRepository->findByField('name', $phone);

        if (empty($user)) {
            return $this->fail(self::VALIDATE_ERROR, '该号未注册');
        }


        if (SmsServices::checkCaptcha($phone, $code, 2)) {
            $info = [
                'password' => encrypt($password)
            ];
            $this->userRepository->update($info, $user['id']);
            return $this->success();

        } else {
            return $this->fail(self::VALIDATE_ERROR, '验证码错误，请重试');
        }
    }


    /**
     * @api {get} api/users/work/type 获取工种列表
     * @apiGroup User
     * @apiName getWorkType
     *
     * @apiHeader {String} Accept=application/json
     * @apiHeader {String} Authorization Bearer xxxxx
     *
     * @apiSampleRequest api/users/work/type
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *    {
     * "code": 0,
     * "msg": "ok",
     * "data": [
     * {
     * "id": 1,
     * "name": "油漆工"
     * }
     * ]
     * }
     **/
    public function getWorkType(Request $request)
    {
        $workType = WorkType::select('id', 'name')->get();
        return $this->success($workType);
    }

}
